package com.intel.factorytest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemProperties;
import android.os.storage.StorageManager;
import android.os.storage.StorageEventListener;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.intel.factorytest.R;
import com.intel.factorytest.activity.SensorsTestActivity.ItemInfo;
import com.intel.factorytest.adapter.GridAdapter;
import com.intel.factorytest.application.MATApplication;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.log.LogWriter;
import com.intel.factorytest.util.SDCardUtil;
import com.intel.factorytest.util.Util;


public class BatteryTest extends BaseActivity {

    private static final String TEST_CASE_NAME = "BatteryTest";
    private static final String TAG = "BatteryTest";

    private boolean doBatteryStatusCheckTest = true;
    private boolean resultBatteryOK = false;
    private boolean resultCharging = false;

    private String confValue;

    // testcase name
    private static final String TC_BatteryStatusCheck = "Battery status check";


    private static final String TC_BatteryStatusCheck_zh = "电池状态检测";


    private static final Map<String, String> nameMapping_language = new HashMap<String, String>();
    static {
    nameMapping_language.put(TC_BatteryStatusCheck,
        TC_BatteryStatusCheck_zh);
    }

    // index
    private static final int INDEX_BatteryStatus = 0;


    // battery status
    private TextView mTextView_Battery;
    private Button mChangeBatteryStatusBtn;
    private static final String voltage_path = "/sys/class/power_supply/max17047_battery/uevent";
    private static final String VOLTAGE_DIRECTORY = "/sys/class/power_supply/";

    private static final String KEY_BATTERY_VOL_THRESHOLD_MIN = "BatteryVoltage_Threshold_MIN";
    private static final String KEY_BATTERY_VOL_THRESHOLD_MAX = "BatteryVoltage_Threshold_MAX";
    private static final String KEY_BATTERY_TEMP_THRESHOLD_MIN = "BatteryTemperature_Threshold_MIN";
    private static final String KEY_BATTERY_TEMP_THRESHOLD_MAX = "BatteryTemperature_Threshold_MAX";
    private static final String KEY_BATTERY_TMP = "BatteryTemperature";
    private static final String KEY_VOL_ERROR_LIMIT = "Voltage_Error_Limitation";
    private static final String KEY_TMP_ERROR_LIMIT = "Temperature_Error_Limitation";

    private float valueBatteryVoltageThresholdMin = 3500f;
    private float valueBatteryVoltageThresholdMax = 4350f;
    private float valueBatteryTemperatureThresholdMin = -10;
    private float valueBatteryTemperatureThresholdMax = 45;
    private float valueTmpErrorLimitation = 3f;



    int scale = 0;
    int plugType = 0;
    int status = 0;
    int health = 0;
    int temperature = 0;
    private Properties properties;

    // Handler Message
    private static final int MSG_CHECK_RESULT = 1;
    TextView batteryText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    properties = ((PropertiesConfParser) ConfigFileParseUtil
        .getConfParserConcrete(this,
            AConfigFileParser.EXTENSION_PROPERTISE))
        .getProperties(isPcba);

    // get battery's configurations
    valueBatteryVoltageThresholdMin = Float.parseFloat(properties
        .getProperty(KEY_BATTERY_VOL_THRESHOLD_MIN,
            String.valueOf(valueBatteryVoltageThresholdMin)));
    valueBatteryVoltageThresholdMax = Float.parseFloat(properties
        .getProperty(KEY_BATTERY_VOL_THRESHOLD_MAX,
            String.valueOf(valueBatteryVoltageThresholdMax)));
    valueBatteryTemperatureThresholdMin = Float.parseFloat(properties
        .getProperty(KEY_BATTERY_TEMP_THRESHOLD_MIN,
            String.valueOf(valueBatteryTemperatureThresholdMin)));
    valueBatteryTemperatureThresholdMax = Float.parseFloat(properties
        .getProperty(KEY_BATTERY_TEMP_THRESHOLD_MAX,
            String.valueOf(valueBatteryTemperatureThresholdMax)));
    valueTmpErrorLimitation = Float.parseFloat(properties.getProperty(
        KEY_TMP_ERROR_LIMIT, String.valueOf(valueTmpErrorLimitation)));

    setContentView(R.layout.battery_test);
    initView();

    if (isSystemTest) {
        Intent intent = getIntent();
        confValue = intent.getStringExtra("value");
        initTestByConfig(confValue);
    } else {
        doBatteryStatusCheckTest = true;
    }
    resultCharging = false;
    resultBatteryOK = false;
    }

    @Override
    protected void initView() {
    super.initView();
    batteryText = (TextView)findViewById(R.id.battery_status);
    mSucBtn.setVisibility(View.INVISIBLE);//add by wangsm
    //mSucBtn.requestFocus();
    }


    private void initTestByConfig(String config) {
    if (config == null || config.trim().length() == 0)
        return;

    Log.i("tangjun comprehensive test", "config = " + config);

    String[] configs = config.split(";");
    for (String conf : configs) {
        String[] items = conf.split("=");

        // overall sensors' switch
        if (items.length == 1) {
        if (items[0].equals("0")) {
            // Don't test any Sensor!
            break;
        }
        continue;
        }

        // single sensor's switch
        boolean doTest = false;
        if (items[1].equals("1")) {
        doTest = true;
        }

        if (items[0].equals(TC_BatteryStatusCheck)) {
        doBatteryStatusCheckTest = doTest;
        }

    }
    }

    @Override
    protected void onResume() {
    super.onResume();
    // register BroadcastReceiver for Battery status
    Log.i(TAG, "onResume doBatteryStatusCheckTest = " + doBatteryStatusCheckTest);
    if (doBatteryStatusCheckTest) {
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mReceiverBatteryInfo, mIntentFilter);
    }
    mItemTestFinish = true;//add by wangsm
    }



    protected void onPause() {
    super.onPause();
    if (doBatteryStatusCheckTest) {
        unregisterReceiver(mReceiverBatteryInfo);
    }
    };

    @Override
    protected void onDestroy() {
    super.onDestroy();
    }

    // #######################################################
    // # BatteryStatus #
    // #######################################################

    private BroadcastReceiver mReceiverBatteryInfo = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        String action = intent.getAction();
        Log.i(TAG, "mReceiverBatteryInfo action = " + action);

        if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
        scale = intent.getIntExtra("voltage", 0);
        plugType = intent.getIntExtra("plugged", 0);
        status = intent.getIntExtra("status",
            BatteryManager.BATTERY_STATUS_UNKNOWN);
        health = intent.getIntExtra("health",
            BatteryManager.BATTERY_HEALTH_UNKNOWN);
        temperature = intent.getIntExtra("temperature",
            BatteryManager.BATTERY_HEALTH_UNKNOWN);
        setSummary(scale, plugType, status, health, temperature);
        }

    }

    };


    private void setSummary(int batteryV, int plugType, int status, int health,
        int temperature) {
    BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
    int capacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    String statusString;
    String healthString;
    if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
        resultCharging = true;
        statusString = this
            .getString(R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_TXT);
        if (plugType > 0) {
        statusString = statusString
            + " "
            + this.getString((plugType == BatteryManager.BATTERY_PLUGGED_AC) ? R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_AC_TXTB
                : R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_USB_TXT);
        is_pass = true;
        mSucBtn.setVisibility(View.VISIBLE);//add by wangsm
        }
    } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
        statusString = this
            .getString(R.string.SERVICEMENU_BATTERY_STATUS_DISCHARGING_TXT);
    } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
        statusString = this
            .getString(R.string.SERVICEMENU_BATTERY_STATUS_NOT_CHARGING_TXT);
    } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
        statusString = this
            .getString(R.string.SERVICEMENU_BATTERY_STATUS_FULL_TXT);
        is_pass = true;
    } else {
        statusString = this
            .getString(R.string.SERVICEMENU_BATTERY_STATUS_UNKNOWN_TXT);
    }

    if (health == BatteryManager.BATTERY_HEALTH_GOOD) {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH_GOOD_TXT);
    } else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH_OVERHEAT_TXT);
    } else if (health == BatteryManager.BATTERY_HEALTH_DEAD) {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH_DEAD_TXT);
    } else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH__OVER_VOLTAGE_TXT);
    } else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE) {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNSPECIFIED_FAILURE_TXT);
    } else {
        healthString = this
            .getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNKNOWN_TXT);
    }
    resultBatteryOK = true;
    StringBuilder mStringBuilder = new StringBuilder();
    mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_CAPACITY_TXT));
    mStringBuilder.append(capacity);
    mStringBuilder.append("%");
    mStringBuilder.append("\n");
    mStringBuilder
        .append(getString(R.string.SERVICEMENU_BATTERY_VOLTAGE_TXT));
    mStringBuilder.append(batteryV);
    mStringBuilder.append("mV");
    if (isSystemTest) {
        if (!checkVoltage(batteryV)) {
        mStringBuilder
            .append(getString(R.string.ComprehensiveInvalidVoltage));
        //mInfoList.get(INDEX_BatteryStatus).isRedBg = true;
        resultBatteryOK = false;
        }
    } else {

    }
    mStringBuilder.append("\n");
    mStringBuilder
        .append(getString(R.string.SERVICEMENU_BATTERY_STATUS_TXT));
    mStringBuilder.append(statusString);
    mStringBuilder.append("\n");
    // drop battery health status
    /*
     * mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_HEALTH_TXT
     * )); mStringBuilder.append(healthString); mStringBuilder.append("\n");
     */
    mStringBuilder
        .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_TXT));
    float convertedTemperature = (float) temperature / 10.0f;
    mStringBuilder.append(convertedTemperature);
    mStringBuilder
        .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_UNIT_TXT));
    if (!checkTemperature(convertedTemperature)) {
        mStringBuilder
            .append(getString(R.string.ComprehensiveInvalidTemperature));
        //mInfoList.get(INDEX_BatteryStatus).isRedBg = true;
        resultBatteryOK = false;
    }
    mStringBuilder.append("\n");
    if (is_pass) {
        mStringBuilder
            .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_OK_TXT)
                + "\n");
    }
    batteryText.setText(mStringBuilder.toString());
    }

    private boolean checkVoltage(float v) {
    System.out.println("tangjun check battery voltage: min="
        + valueBatteryVoltageThresholdMin + ",max="
        + valueBatteryVoltageThresholdMax);
    return v >= valueBatteryVoltageThresholdMin
        && v <= valueBatteryVoltageThresholdMax;
    }

    private boolean checkTemperature(float t) {
    System.out.println("tangjun check battery voltage: min="
        + valueBatteryTemperatureThresholdMin + ",max="
        + valueBatteryTemperatureThresholdMax);
    return t >= valueBatteryTemperatureThresholdMin
        && t <= valueBatteryTemperatureThresholdMax;
    }


    @Override
    public void finish() {

    super.finish();
    }




}
